import 'package:flutter/material.dart';
import 'package:forme/models/git_commit.dart';

import '../services/api_service.dart';
import '../utils/date_util.dart';

class GitLogScreen extends StatefulWidget {
  final String owner;
  final String repo;
  final String branch;

  const GitLogScreen(this.owner, this.repo, this.branch, {super.key});

  @override
  _GitLogScreenState createState() => new _GitLogScreenState();
}

class _GitLogScreenState extends State<GitLogScreen> {
  final ApiService _apiService = ApiService();
  final List<GitCommit> _repos = [];
  var _isLoading = false;
  int _currentPage = 1;
  bool _hasMore = true;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    loadData();
    _scrollController.addListener(_onScroll);
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> loadData({bool refresh = true}) async {
    if (_isLoading) return;
    setState(() {
      _isLoading = true;
      if (refresh) {
        _currentPage = 1;
        _repos.clear();
      }
    });
    final newRepos = await _apiService.getGitLog(
        widget.owner, widget.repo, widget.branch, _currentPage);
    setState(() {
      if (refresh) {
        _repos.clear();
      }
      _repos.addAll(newRepos);
      _hasMore = newRepos.isNotEmpty;
      _currentPage++;
      _isLoading = false;
    });
  }

  void _onScroll() {
    if (_scrollController.position.pixels >=
        _scrollController.position.maxScrollExtent - 200) {
      if (!_isLoading && _hasMore) {
        loadData(refresh: false);
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('提交记录'),
      ),
      body: RefreshIndicator(
        onRefresh: loadData,
        child: ListView.builder(
          controller: _scrollController,
          itemCount: _repos.length + (_hasMore ? 1 : 0),
          itemBuilder: (context, index) {
            if (index == _repos.length) {
              return const Center(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: CircularProgressIndicator(),
                ),
              );
            }
            final repo = _repos[index];
            return ListTile(
              contentPadding:
                  const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              leading: CircleAvatar(
                radius: 16,
                backgroundColor: Colors.blue[100],
                child: Text(
                  repo.commit.author.name.substring(0, 1).toUpperCase(),
                  style: TextStyle(
                    color: Colors.blue[800],
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              title: Text(
                repo.commit.message.split('\n').first,
                maxLines: 2,
                overflow: TextOverflow.ellipsis,
              ),
              subtitle: Row(
                children: [
                  Text(
                    repo.sha.substring(0, 7),
                    style: const TextStyle(
                      fontFamily: 'monospace',
                      fontSize: 13,
                      color: Colors.grey,
                    ),
                  ),
                  const SizedBox(width: 12),
                  Expanded(
                    child: Text(
                      '${repo.commit.author.name} • ${DateUtil.formatTimeAgo(repo.commit.author.date)}',
                      style: const TextStyle(
                        fontSize: 13,
                        color: Colors.grey,
                      ),
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ),
    );
  }
}
